package Grasnador.Grasnador0.Generic;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Grasnador.Grasnador0.util.HibernateUtil;

public abstract class GenericDAO<T> {

	@SuppressWarnings("rawtypes")
	private final Class typeClass;
	Transaction tx = null;

	@SuppressWarnings("rawtypes")
	public GenericDAO(Class argClass) {
		typeClass = argClass;
	}

	public boolean insert(T obj) {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(obj);
			session.getTransaction().commit();
		} finally {
			session.close();
		}

		return true;
	}

	public boolean update(T obj) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.merge(obj);
		session.getTransaction().commit();
		return true;
	}

	public boolean delete(T obj) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.flush();
			session.clear();
			tx = session.getTransaction();
			session.delete(obj);
			session.getTransaction().commit();
			return true;
		} catch (RuntimeException e) {
			if (tx != null) {
				tx.rollback();
			}
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public T getById(long id) {
		T obj = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		obj = (T) session.get(typeClass, id);
		session.getTransaction().commit();
		return obj;
	}

	public abstract List<T> getByName(String name);

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		java.util.List<T> lista = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		lista = session.createCriteria(typeClass).list();
		session.getTransaction().commit();
		return lista;
	}

}